<!-- 游戏输赢 -->
<template>
  <SearchTable :query="data.query" :list="data.list" :total="data.total" :showExport="true" @changeSize="changeSize"
    @changePage="changePage" @search="getSearchList()" @reset="onHideDetails(true)" @download="getExport"
    @changeTh="data.dialogVisible = true">
    <template #form>
      <Operator ref="OperatorRef" @query="queryItem" />
      <GameItem ref="GameItemRef" @query="queryGame" />
      <el-form-item label="高倍返奖倍数：">
        <el-input-number :min="1" :max="100000" :precision="0" v-model="data.query.bonus_multiple"
          placeholder="请输入高倍返奖倍数" clearable :controls="false" />
      </el-form-item>
      <el-form-item label="日期时间：">
        <el-date-picker v-model="data.query.date" type="date" range-separator="-" placeholder="请选择时间"
          value-format="YYYY-MM-DD" :clearable="false" />
      </el-form-item>
    </template>
    <template #button>
      <el-button type="warning" @click="data.query.is_usdt_show = data.query.is_usdt_show ? 0 : 1, getSearchList()">{{
        data.query.is_usdt_show ? '取消换算' : '换算USDT' }}</el-button>
    </template>
    <template #table>
      <template v-for="(item, index) in data.fields" :key="index">
        <el-table-column :prop="item.prop" :label="item.label" :width="item.width" show-overflow-tooltip
          :sortable="item.sortable ? true : false">
          <template #header>
            <el-tooltip v-if="item.tips" effect="dark" placement="top">
              <template #content>
                <div v-html="item.tips"></div>
              </template>
              <el-icon class="ques-tips">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            {{ item.label }}
          </template>
          <template v-if="item.prop == 'game_id'" #default="scope">
            <el-tooltip effect="light" placement="bottom">
              <template #content>
                <div class="flexWrap">
                  <div v-for="(second, two) in scope.row.agent_list">
                    【{{ second }}】{{ selectToLabel(indexStore.agentArray, second) }}
                  </div>
                </div>
              </template>
              <GameHeaderInfo :game_id="scope.row.game_id" />
            </el-tooltip>
          </template>
          <template v-if="item.prop == 'rtp'" #default="scope">
            【{{ scope.row.rtp_type?selectToLabel(RtpType, scope.row.rtp_type):'-' }}】{{ scope.row.rtp ? BigHundred(scope.row.rtp) + '%' : '-' }} / {{ scope.row.game_rtp }} / {{ scope.row.history_rtp }}
          </template>
          <template v-if="item.prop == 'bonus_multiple_count'" #default="scope">
            <span class="item_details" @click="checkDetails(scope.row)">
              {{ scope.row.bonus_multiple_count }}
            </span>
          </template>
          <template v-if="item.prop == 'game_income'" #default="scope">
            <span :class="colorClass(scope.row.game_income)">
              {{ BigWan(scope.row.game_income) }}</span>
          </template>
          <template v-if="item.prop == 'history_game_income'" #default="scope">
            <span :class="colorClass(scope.row.history_game_income)">
              {{ BigWan(scope.row.history_game_income) }}</span>
          </template>
          <template v-if="item.prop == 'game_bet'" #default="scope">
            <span class="colorText">{{ BigWan(scope.row.game_bet) }}</span>
          </template>
          <template v-if="item.prop == 'history_game_bet'" #default="scope">
            <span :class="colorClass(scope.row.history_game_bet)">
              {{ BigWan(scope.row.history_game_bet) }}</span>
          </template>
        </el-table-column>
      </template>
      <el-table-column fixed="right" label="操作" width="90" align="center">
        <template #header>
          <el-tooltip effect="dark" content="点击查看投注记录详情" placement="top">
            <el-icon class="ques-tips">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
          详情
        </template>
        <template #default="scope">
          <el-button type="primary" v-permiss="'/system/destroyManager'" size="small"
            @click="checkGearDetails(scope.row)">
            详情
          </el-button>
        </template>
      </el-table-column>
    </template>
  </SearchTable>

  <!-- 变更表头弹框 -->
  <tableHeader :dialogVisible="data.dialogVisible" :list="data.fields" @cancel="data.dialogVisible = false"
    @resetData="resetData"></tableHeader>

  <!-- 人数详情 -->
  <el-dialog v-model="data.isShowDetails" width="60%" title="人数详情" :close-on-click-modal="false"
    :close-on-press-escape="false" @close="onHideDetails" top="10vh">
    <div v-loading="indexStore.moduleLoading" class="dialogMax">
      <SearchTable :query="data.queryDetails" :list="data.listDetails" :total="data.totalDetails" :showSet="false"
        :showFromQuery="false" @changeSize="changeSizeDetails" @changePage="changePageDetails"
        @reset="onHideDetails(true)" @search="getSearchDetailsList">
        <template #form>
          <el-form-item label="">
            <p class="box-title mustPass">
              【{{ data.query.date }}】 <GameHeaderInfo :game_id="data.checkedItem.game_id" />
            </p>
            <span class="marginL20">高倍返奖总人数：<span class="mustPass">{{ data.checkedItem.bonus_multiple_count }}</span>人</span>
          </el-form-item>
        </template>
        <template #table>
          <template v-for="(item, index) in data.fieldDetails" :key="index">
            <el-table-column :prop="item.prop" :label="item.label" :width="item.width" show-overflow-tooltip>
              <template #header>
                <el-tooltip v-if="item.tips" effect="dark" placement="top">
                  <template #content>
                    {{ item.tips }}
                  </template>
                  <el-icon class="ques-tips">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
                {{ item.label }}
              </template>
              <template v-if="item.prop == 'save_time_stamp'" #default="scope">
                {{ setTimestampTime(scope.row.save_time_stamp) }}
              </template>
              <template v-if="item.prop == 'bet'" #default="scope">
                <span :class="colorClass(scope.row.bet)">
                  {{ BigWan(scope.row.bet) }}</span>
              </template>
              <template v-if="item.prop == 'win'" #default="scope">
                <span :class="colorClass(scope.row.win)">
                  {{ BigWan(scope.row.win) }}</span>
              </template>
              <template v-if="item.prop == 'bonus_multiple_count'" #default="scope">
                <span class="colorText">
                  {{ BigInteger(BigDiv(scope.row.win, scope.row.bet)) }}</span>
              </template>
            </el-table-column>
          </template>
        </template>
      </SearchTable>
    </div>
  </el-dialog>

  <!-- 投注档位详情 -->
  <el-dialog v-model="data.isShowGear" width="65%" title="投注档位详情" :close-on-click-modal="false"
    :close-on-press-escape="false" @close="onHideDetails" top="13vh">
    <template #header>
      <p class="box-title mustPass marginT20 flex">
        【{{ data.query.date }}】 <GameHeaderInfo :game_id="data.checkedItem.game_id" />
      </p>
    </template>
    <div v-loading="indexStore.moduleLoading" class="dialogMaxHeight">
      <SearchTable :list="data.gearDetailsList" :total="0" :showSet="false" :showFromQuery="false">
        <template #form></template>
        <template #table>
          <template v-for="(item, index) in data.gearDetails" :key="index">
            <el-table-column :prop="item.prop" :label="item.label" :width="item.width" show-overflow-tooltip>
              <template #header>
                <el-tooltip v-if="item.tips" effect="dark" placement="top">
                  <template #content>
                    {{ item.tips }}
                  </template>
                  <el-icon class="ques-tips">
                    <QuestionFilled />
                  </el-icon>
                </el-tooltip>
                {{ item.label }}
              </template>
              <template v-if="item.prop == 'position'" #default="scope">
                第{{ scope.row.position + 1 }}档
              </template>
              <template v-if="item.prop == 'bet_money_rate'" #default="scope">
                {{ BigTimeHundred(scope.row.bet_money_rate) }}%
              </template>
              <template v-if="item.prop == 'bet_count_rate'" #default="scope">
                {{ BigTimeHundred(scope.row.bet_count_rate) }}%
              </template>
              <template v-if="item.prop == 'bet'" #default="scope">
                <span class="colorText"> {{ BigWan(scope.row.bet) }}</span>
              </template>
              <template v-if="item.prop == 'bet_money'" #default="scope">
                <span class="colorText"> {{ BigWan(scope.row.sum_bet) }}</span>
              </template>
              <template v-if="item.prop == 'sum_win'" #default="scope">
                <span :class="colorClass(scope.row.sum_win)"> {{ BigWan(scope.row.sum_win) }}</span>
              </template>
              <template v-if="item.prop == 'game_income'" #default="scope">
                <span :class="colorClass(scope.row.game_income)"> {{ BigWan(scope.row.game_income) }}</span>
              </template>
              <template v-if="item.prop == 'rtp'" #default="scope">
                {{ RtpPercent(scope.row.sum_win,scope.row.sum_bet) }}
              </template>
            </el-table-column>
          </template>
        </template>
      </SearchTable>
    </div>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import Operator, { type QueryType } from '@/components/FormItem/Operator.vue'
import GameItem, { type GameType } from '@/components/FormItem/GameItem.vue'
import tableHeader from '@/components/tableHeader/tableHeader.vue'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import GameHeaderInfo from '@/components/FormItem/GameHeaderInfo.vue'
import { exportToExcel } from '@/utils/export'
import { RtpType } from '@/config/eunm'
import { selectToLabel, colorClass, CurrencyExchange } from '@/utils/index'
import { BigHundred, BigWan, RtpPercent, BigDiv, BigInteger, BigTimes, BigTimeHundred } from '@/utils/math'
import { setTimestampTime, getDateDay, setTimeDateValue } from '@/utils/time'
import { getGameWin, getGameWinDetails, getGearDetails } from '@/api/gameReport'

import { useStore } from '@/stores/index'
const indexStore = useStore()

const data = reactive({
  query: {
    page: 1,
    size: 50,
    agent_id: -1,
    operated_id: -1,
    platform: -1,
    game_id: -1,
    currency_id: -1,
    is_usdt_show: 0,
    bonus_multiple: 50,
    date: getDateDay(0)
  },
  list: [],
  total: 0,
  fields: [
    { label: '游戏名称', prop: 'game_id', width: '200', tips: '游戏名称的描述说明' },
    { label: 'RTP:设定/当前/历史', prop: 'rtp', width: '250', tips: '游戏RTP显示' },
    { label: '当天输赢', prop: 'game_income', width: '180', sortable: true, tips: '游戏在筛选日期的当天输赢情况正为盈利、负为亏损' },
    { label: '历史输赢', prop: 'history_game_income', width: '180', sortable: true, tips: '游戏历史总输赢情况正为盈利、负为亏损跟筛选日期无关' },
    { label: '投注用户', prop: 'valid_user', width: '140', sortable: true, tips: '游戏当天有过下注行为的玩家数量去重' },
    { label: '历史投注用户', prop: 'history_valid_user', width: '170', sortable: true, tips: '游戏历史下注玩家数量总和，去重' },
    { label: '在线人数', prop: 'online_count', width: '170', sortable: true, tips: '游戏在线人数' },
    { label: '投注金额', prop: 'game_bet', width: '160', sortable: true, tips: '游戏当天的下注金额总和' },
    { label: '历史投注金额', prop: 'history_game_bet', width: '170', sortable: true, tips: '游戏历史下注金额总和' },
    { label: '游戏次数', prop: 'game_count', width: '140', sortable: true, tips: '玩家当天在游戏的游戏次数' },
    { label: '历史游戏次数', prop: 'history_game_count', width: '170', sortable: true, tips: '所有玩家历史游戏次数' },
    { label: '高倍返奖人数', prop: 'bonus_multiple_count', width: '170', sortable: true, tips: '分游戏统计爆大奖的人数，点击可查看人数详情<br/>大奖默认倍数为50倍可在上方输入框自定义编辑' },
  ],
  dialogVisible: false,
  isShowDetails: false,
  isShowGear: false,
  checkedItem: {} as any,
  queryDetails: {
    page: 1,
    size: 50,
    agent_id: -1,
    operated_id: -1,
    game_id: -1,
    currency_id: -1,
    bonus_multiple: 50,
    date: getDateDay(0)
  },
  listDetails: [],
  totalDetails: 0,
  fieldDetails: [
    { label: '日期', prop: 'save_time_stamp', width: '180', tips: '筛选日期展示' },
    { label: '平台ID', prop: 'account_id', width: '150', tips: '玩家ID编号，唯一' },
    { label: '下注金额', prop: 'bet', width: '', tips: '高倍返奖当局的下注金额' },
    { label: '返奖金额', prop: 'win', width: '', tips: '高倍返奖当局的返奖金额' },
    { label: '倍数', prop: 'bonus_multiple_count', width: '150', tips: '当局返奖倍数' },
  ],
  gearDetails: [
    { label: '档位', prop: 'position', width: '100' },
    { label: '玩家投注档位', prop: 'bet', width: '150', tips: '此游戏在筛选日期内产生的投注档位，去重' },
    { label: '投注金额', prop: 'bet_money', width: '', tips: '每个投注档位的投注金额和' },
    { label: '投注金额占比', prop: 'bet_money_rate', width: '150', tips: '每个投注金额/此游戏在筛选日期内的总下注' },
    { label: '投注次数', prop: 'bet_count', width: '', tips: '每档投注的下注次数' },
    { label: '投注次数占比', prop: 'bet_count_rate', width: '150', tips: '每档投注次数/此游戏总下注次数' },
    { label: '游戏返奖', prop: 'sum_win', width: '', tips: '每档投注的游戏返奖情况' },
    { label: '游戏输赢', prop: 'game_income', width: '', tips: '每档投注的游戏输赢情况' },
    { label: '游戏RTP', prop: 'rtp', width: '', tips: '每档投注的游戏RTP情况' },
  ],
  gearDetailsList: [],
})

// 商户类别 + 商户
const queryItem = (item: QueryType) => {
  data.query.agent_id = item.agent_id
  data.query.operated_id = item.operated_id
}
// 游戏品牌 + 游戏
const queryGame = (item: GameType) => {
  data.query.platform = item.platform
  data.query.game_id = item.game_id
}

onMounted(async () => {
  getSearchList()
})

const getSearchList = async () => {
  indexStore.setPageLoading(true)
  let query = JSON.parse(JSON.stringify(data.query))
  query = setTimeDateValue(query)
  query.bonus_multiple = Number(query.bonus_multiple)
  let res = await getGameWin(query)
  res.data?.forEach((item: any) => {
    item.game_rtp = RtpPercent(item.game_win, item.game_bet)
    item.history_rtp = RtpPercent(item.history_game_win, item.history_game_bet)
  })
  data.list = res.data
}

// 查看高倍返奖人数
const checkDetails = async (row: any) => {
  if (!row.bonus_multiple_count) return ElMessage.error('暂无数据')
  data.queryDetails.date = data.query.date
  data.queryDetails.game_id = row.game_id
  data.queryDetails.agent_id = data.query.agent_id
  data.queryDetails.bonus_multiple = data.query.bonus_multiple
  data.isShowDetails = true
  data.checkedItem = row
  getSearchDetailsList()
}
const getSearchDetailsList = async () => {
  indexStore.setModuleLoading(true)
  data.gearDetailsList = []
  let query = JSON.parse(JSON.stringify(data.queryDetails));
  query = setTimeDateValue(query)
  let res = await getGameWinDetails(query)
  res.data?.list?.forEach((item: any) => {
    item.date = data.query.date
    if (data.query.is_usdt_show) {
      item.bet = BigTimes(item.bet, CurrencyExchange(item.agent_id))
      item.win = BigTimes(item.win, CurrencyExchange(item.agent_id))
    }
  })
  data.listDetails = res.data.list
  data.totalDetails = res.data.total
}

// 查看详情况
const checkGearDetails = async (row: any) => {
  data.checkedItem = row
  data.isShowGear = true
  getSearchGearDetailsList()
}
const getSearchGearDetailsList = async () => {
  indexStore.setModuleLoading(true)
  let query = JSON.parse(JSON.stringify(data.query));
  query = setTimeDateValue(query)
  let res = await getGearDetails({
    operated_id: query.operated_id,
    agent_id: query.agent_id,
    game_id: data.checkedItem.game_id,
    start_time: query.start_time,
    end_time: query.end_time,
  })
  res.data?.forEach((item: any, index: number) => {
    item.position = index
  })
  data.gearDetailsList = res.data
}

// 导出
const getExport = async () => {
  let query = JSON.parse(JSON.stringify(data.query))
  query.page = 1
  query.size = 10000
  query = setTimeDateValue(query)
  let res = await getGameWin(query)
  let dataList = res.data
  let header: string[] = []
  let list: never[][] = []

  data.fields?.forEach((item) => {
    header.push(item.label)
  })
  dataList?.forEach((item: { [x: string]: any }, index: any) => {
    let arr: never[] = []
    data.fields?.forEach((x) => {
      switch (x.prop) {
        case 'game_id':
          arr.push(selectToLabel(indexStore.gameArray, item[x.prop]) as never)
          break
        case 'rtp':
          arr.push(('【'+item['rtp_type']?selectToLabel(RtpType,item['rtp_type']):'-'+'】'+(item[x.prop]?BigHundred(item[x.prop])+'%':'-')+'/'+item['game_rtp']+'/'+item['history_rtp']) as never)
          break
        case 'game_income':
          arr.push(BigWan(item[x.prop]) as never)
          break
        case 'history_game_income':
          arr.push(BigWan(item[x.prop]) as never)
          break
        case 'game_bet':
          arr.push(BigWan(item[x.prop]) as never)
          break
        case 'history_game_bet':
          arr.push(BigWan(item[x.prop]) as never)
          break
        // case 'game_rtp':
        //   arr.push(RtpPercent(BigWan(item['game_win']), BigWan(item['game_bet'])) as never)
        //   break
        // case 'history_rtp':
        //   arr.push(RtpPercent(BigWan(item['history_game_win']), BigWan(item['history_game_bet'])) as never)
        //   break
        default:
          arr.push(item[x.prop] as never)
          break
      }
    })
    list.push(arr)
  })
  exportToExcel(list, header, '游戏输赢')
}

// 修改页数
const changeSize = (val: number) => {
  data.query.size = val
}
const changePage = (val: number) => {
  data.query.page = val
  getSearchList()
}
const changePageDetails = (val: number) => {
  data.queryDetails.page = val
  getSearchDetailsList()
}
const changeSizeDetails = (val: number) => {
  data.queryDetails.size = val
}

// 重置表头
const resetData = (val: any) => {
  data.fields = val
}

// 重置
const OperatorRef = ref<any>()
const GameItemRef = ref<any>()
const onHideDetails = (show: boolean) => {
  data.isShowDetails = false
  data.isShowGear = false
  if (show) {
    data.query = {
      page: 1,
      size: 50,
      agent_id: -1,
      operated_id: -1,
      platform: -1,
      game_id: -1,
      currency_id: -1,
      is_usdt_show: 0,
      bonus_multiple: 50,
      date: getDateDay(0)
    }
    OperatorRef.value.onHideDetails()
    GameItemRef.value.onHideDetails(-1)
    getSearchList()
  }
}
</script>

<style scoped lang="scss">
.flexWrap {
  max-width: 200px;
  max-height: 300px;
  overflow: auto;
}
</style>
